/*
 * 功能说明：
 * 作者：Fish
 * 创建时间：Jun 3, 2013
 * Copyright © Tiancom Co.Ltd All Rights Reserved
 */
package com.owen.he.jee.dao.impl.ibatis;

import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ibatis.sqlmap.engine.type.BaseTypeHandler;
import com.ibatis.sqlmap.engine.type.TypeHandler;

public class ObjectTypeHandler extends BaseTypeHandler implements TypeHandler {

	/**
     * @see TypeHandler#setParameter(PreparedStatement, int, Object, String)
     */
    public void setParameter(PreparedStatement ps, int i, Object parameter, String jdbcType) 
    throws SQLException {
        ps.setObject(i, parameter);
    }

    /**
     * @see TypeHandler#getResult(ResultSet, String)
     */
    public Object getResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return fix(object);
        }
    }

    /**
     * @see TypeHandler#getResult(ResultSet, int)
     */
    public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
        Object object = rs.getObject(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return fix(object);
        }
    }

    /**
     * @see TypeHandler#getResult(CallableStatement, int)
     */
    public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object object = cs.getObject(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return fix(object);
        }
    }

    /**
     * @see TypeHandler#valueOf(String)
     */
    public Object valueOf(String s) {
        return s;
    }

    /**
     * 配置类型转换
     * 
     * @param obj
     *            　object from oracle jdbc driver
     * @return object of suitable java datatype
     */
    protected Object fix(Object obj) {
        try {
        	if (obj instanceof BigDecimal) {
                return ((BigDecimal)obj).toPlainString();
            }else{
            	return obj.toString();
            }
        } catch (Exception e) {
        	e.printStackTrace();
            return obj;
        }
    }
}
